package com.hqyj.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.config.PayConfig;
import com.hqyj.dao.TbParkingUseMapper;
import com.hqyj.pojo.Cash;
import com.hqyj.pojo.TbDevice;
import com.hqyj.pojo.TbParkingUse;
import com.hqyj.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
 * @description:
 * @author: GP
 * @date: 2021/10/7-23:37
 */
@Service
public class PayServiceImpl implements PayService {

    //支付配置
    @Autowired
    private AlipayClient alipayClient;

    //读取payConfig文件的注入
    @Autowired
    private PayConfig payConfig;

    @Autowired
    private TbParkingUseMapper tbParkingUseMapper;

    @Override
    public HashMap<String, Object> payDevice(TbDevice tbDevice) {
        //后端调用支付宝接口获取到的数据发送到前端(front)
        HashMap<String, Object> front = new HashMap<>();
        //前端获取的数据存入map中，发送给支付宝接口调用
        HashMap<String, Object> map = new HashMap<>();
        //订单编号
        //根据时间戳+随机0-10的数生成一个唯一的订单
        Long order = System.currentTimeMillis() + (int) (Math.random() * 10);
        map.put("out_trade_no", order);
        //付款金额
        map.put("total_amount", tbDevice.getUnitPrice());
        //商品名称
        map.put("subject", tbDevice.getName());
        //订单描述
        map.put("body", "预计使用年限:"+tbDevice.getExpectedUsefulLife());

        try {
            //把请求参数转换成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonParams = objectMapper.writeValueAsString(map);

            //设置阿里表单支付请求对象
            AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
            //设置参数
            alipayRequest.setBizContent(jsonParams);
            //设置支付成功返回的回调地址
            alipayRequest.setReturnUrl(payConfig.getReturnUrl());
            //设置异步回调的地址
            alipayRequest.setNotifyUrl(payConfig.getNotifyUrl());

            //获取支付宝支付响应对象
            AlipayTradePrecreateResponse alipayResponse = alipayClient.execute(alipayRequest);
            System.out.println(alipayResponse.toString());

            if (alipayResponse.isSuccess()) {
                System.out.println("二维码支付地址：" + alipayResponse.getQrCode());
                front.put("url", alipayResponse.getQrCode());
            } else {
                front.put("url", "error");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return front;
    }

    @Override
    public HashMap<String, Object> payPark(TbParkingUse tbParkingUse) {

        //后端调用支付宝接口获取到的数据发送到前端(front)
        HashMap<String, Object> front = new HashMap<>();
        //前端获取的数据存入map中，发送给支付宝接口调用
        HashMap<String, Object> map = new HashMap<>();
        //订单编号
        //根据时间戳+随机0-10的数生成一个唯一的订单
        Long order = System.currentTimeMillis() + (int) (Math.random() * 10);
        map.put("out_trade_no", order);
        //付款金额
        map.put("total_amount", Integer.parseInt(tbParkingUse.getUseType()) * 5000);
        //商品名称
        map.put("subject", "停车位" + tbParkingUse.getCode());
        //订单描述
        map.put("body", "购买该停车位" + tbParkingUse.getUseType() + "年");

        try {
            //把请求参数转换成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonParams = objectMapper.writeValueAsString(map);

            //设置阿里表单支付请求对象
            AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
            //设置参数
            alipayRequest.setBizContent(jsonParams);
            //设置支付成功返回的回调地址
            alipayRequest.setReturnUrl(payConfig.getReturnUrl());
            //设置异步回调的地址
            alipayRequest.setNotifyUrl(payConfig.getNotifyUrl());

            //获取支付宝支付响应对象
            AlipayTradePrecreateResponse alipayResponse = alipayClient.execute(alipayRequest);
            System.out.println(alipayResponse.toString());

            if (alipayResponse.isSuccess()) {
                System.out.println("二维码支付地址：" + alipayResponse.getQrCode());
                front.put("url", alipayResponse.getQrCode());
            } else {
                front.put("url", "error");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return front;
    }


    @Override
    public HashMap<String, Object> cash(Cash cash) {
        HashMap<String, Object> mmm = new HashMap<String, Object>();

        HashMap<String, Object> map = new HashMap<>();
        //订单编号
        Long order = System.currentTimeMillis() + (int) (Math.random() * 10);
        map.put("out_trade_no", order);
        //金额
        map.put("total_amount", cash.getMoney());
        //名称
        map.put("subject", cash.getName());
        //描述
        map.put("body", cash.getBody());
        try {
            //把请求参数转换成json字符串格式
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonParams = objectMapper.writeValueAsString(map);

            // 设置阿里表单支付请求对象
            AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
            //设置参数
            alipayRequest.setBizContent(jsonParams);
            //设置支付成功返回的回调地址
            alipayRequest.setReturnUrl(payConfig.getReturnUrl());
            //设置异步回调的地址
            alipayRequest.setNotifyUrl(payConfig.getNotifyUrl());

            //获取支付宝支付响应对象
            AlipayTradePrecreateResponse alipayResponse = alipayClient.execute(alipayRequest);
            System.out.println(alipayResponse.toString());

            if (alipayResponse.isSuccess()) {
                System.out.println("二维码支付地址=" + alipayResponse.getQrCode());
                mmm.put("url", alipayResponse.getQrCode());
            } else {
                mmm.put("url", "error");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return mmm;
    }

    @Override
    public HashMap<String, Object> payParkingFee(TbParkingUse tbParkingUse) {
        //后端调用支付宝接口获取到的数据发送到前端(front)
        HashMap<String, Object> front = new HashMap<>();
        //前端获取的数据存入map中，发送给支付宝接口调用
        HashMap<String, Object> map = new HashMap<>();
        //订单编号
        //根据时间戳+随机0-10的数生成一个唯一的订单
        Long order = System.currentTimeMillis() + (int) (Math.random() * 10);
        map.put("out_trade_no", order);
        //付款金额：一块钱一小时
        int totalFee;
        //获取出车和停车的时间戳
        //查询出数据库后台没有购买停车位和停车了但未出车的数据
        Long temp =0L;
        List<TbParkingUse> list = tbParkingUseMapper.selectByCarNumber(tbParkingUse.getCarNumber());
        Iterator<TbParkingUse> iterator = list.iterator();
        while(iterator.hasNext()){
            TbParkingUse next = iterator.next();
            if(next.getEndTime() == null){
                temp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) - next.getStartTime().toEpochSecond(ZoneOffset.of("+8"));
            }
        }
        //将时间戳转化成时间
        LocalDateTime dateTime =LocalDateTime.ofEpochSecond(temp,0, ZoneOffset.ofHours(0));
        if(dateTime.getSecond()>0){
            totalFee=dateTime.getHour()+1;
        }else{
            totalFee=dateTime.getHour();
        }
        //付款金额
        map.put("total_amount", totalFee);
        //商品名称
        map.put("subject", "停车时长" + dateTime.getHour()+":"+dateTime.getMinute()+":"+dateTime.getMinute());
        //订单描述
        map.put("body", "支付的停车费用" + tbParkingUse.getUseType() + "元");

        try {
            //把请求参数转换成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonParams = objectMapper.writeValueAsString(map);
            //设置阿里表单支付请求对象
            AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
            //设置参数
            alipayRequest.setBizContent(jsonParams);
            //设置支付成功返回的回调地址
            alipayRequest.setReturnUrl(payConfig.getReturnUrl());
            //设置异步回调的地址
            alipayRequest.setNotifyUrl(payConfig.getNotifyUrl());
            //获取支付宝支付响应对象
            AlipayTradePrecreateResponse alipayResponse = alipayClient.execute(alipayRequest);
            System.out.println(alipayResponse.toString());

            if (alipayResponse.isSuccess()) {
                System.out.println("二维码支付地址：" + alipayResponse.getQrCode());
                front.put("url", alipayResponse.getQrCode());
            } else {
                front.put("url", "error");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return front;
    }
}
